const koaBody = require('koa-body');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
process.env.NODE_ENV = `${process.env.PROFILE || 'dev'}`;
console.info('运行环境: %s', process.env.NODE_ENV);
global.config = require('config');
global.Res = require('../../src/utils/res-util');
global.Mes = require('../../src/utils/message-util');
const moment = require('moment-timezone');
global.momentTimezone = moment.tz.setDefault('Asia/Shanghai');

const { sequelize } = require('../libs/mysql');
sequelize.authenticate().then(() => {
  console.info('数据库连接成功！');
}).catch((error) => {
  console.error('数据库连接失败！', error);
});

module.exports = (app) => {
  app.use(cors());
  app.use(koaBody({multipart: true}));
  app.use(bodyParser());
  app.use(async (ctx, next) => {
    try {
      await next();
    } catch (err) {
      ctx.status = err.statusCode || err.status || 500;
      console.info(err.statusCode);
      console.info(err.message);
      ctx.body = {
        message: err.message,
      };
    }
  });

  app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
  });

  app.use(require('../middleware/jwt'));
};
